package com.Optional使用;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.Supplier;

/***
 * @ClassName: Optional使用
 * @Description: 找到名字不是“ddd”且分数小于10的
 * @Auther: tanggy3
 * @Date: 14:33 2023/2/22
 * @version : V1.0
 */
public class OptionalTest {
    public static void main(String[] args) {
        Car aaa = new Car("aaa", 20);
        Car aaa1 = new Car("aaa", 1);
        Car aaa2 = new Car("aaa", 5);
        Car ddd = new Car("ddd", 8);
        Car bbb = new Car("bbb", null);
        Car ccc = new Car();
        ArrayList<Car> cars = new ArrayList<>(7);
        //cars.add(null);
//        cars.add(new Car(null, null));
//        cars.add(bbb);
//        cars.add(ccc);
        cars.add(aaa);
        cars.add(aaa1);
        cars.add(aaa2);
        cars.add(ddd);



        //cars.stream().forEach(System.out::println);//打印所有的
        //System.out.println(cars.stream().findFirst().get());//第一个
        //cars.stream().sorted((o1, o2) -> o1.value > o2.value ? 1 : -1).forEach(System.out::println);//排序会出问题，NPE
        //show(cars);
        cars.stream().filter(c->!"ddd".equals(c.name)).filter(c->c.value<10).sorted((o1, o2) -> o1.value > o2.value ? 1 : -1).forEach(System.out::println);
    }

    public static void show(ArrayList<Car> cars) {
        //找到名字不是“ddd”且分数小于10的
        //不使用Optional，但是使用流
/*        cars.stream().filter(new Predicate<>() {
            @Override
            public boolean test(Car car) {
                if (!car.name.equals("ddd") && car.value < 10) {
                    return true;
                } else {
                    return false;
                }
            }
        }).forEach(System.out::println);

        //不使用Optional，老方法判断空
        for (Car car : cars) {
            if (car != null) {
                if (car.name != null && car.name != "ddd") {
                    if(car.value!=null && car.value<10)
                        System.out.println(car);
                }
            }
        }*/

        //使用Optional
        for (Car car : cars) {
            Optional<Car> carOptional = Optional.ofNullable(car);
            System.out.println(carOptional.filter(c -> !c.name.equals("ddd"))
                    .filter(c -> c.value < 10).orElseGet(new Supplier<Car>() {
                        @Override
                        public Car get() {
                            return new Car("error",500);
                        }
                    }));
        }


    }
}

class Car {
    public String name;
    public Integer value;

    public Car(String name, Integer value) {
        this.name = name;
        this.value = value;
    }

    public Car() {
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", value=" + value +
                '}';
    }
}
